package com.jayam.gas.client.controller;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HasWidgets;
import com.jayam.gas.client.OrderServiceAsync;
import com.jayam.gas.client.event.AddOrderEvent;
import com.jayam.gas.client.event.AddOrderEventHandler;
import com.jayam.gas.client.presenter.AddOrderPresenter;
import com.jayam.gas.client.view.AddOrderViewImpl;
import com.jayam.gas.shared.OrderDetails;

public class AppController implements com.jayam.gas.client.presenter.Presenter, ValueChangeHandler<String> {
	private final HandlerManager eventBus;
	private final OrderServiceAsync rpcService;
	private HasWidgets container;

	public AppController(final OrderServiceAsync rpcService, final HandlerManager eventBus) {
		this.eventBus = eventBus;
		this.rpcService = rpcService;
		bind();
	}

	private void bind() {
		History.addValueChangeHandler(this);

		eventBus.addHandler(AddOrderEvent.TYPE, new AddOrderEventHandler() {
			@Override
			public void onAddOrder(final AddOrderEvent event) {
				doAddNewContact();
			}
		});

	}

	private void doAddNewContact() {
		Window.alert("doaddnewcontact");
		History.newItem("add");
		new AddOrderPresenter(rpcService, eventBus, new AddOrderViewImpl<OrderDetails>()).go(container);
	}

	@Override
	public void go(final HasWidgets container) {
		this.container = container;
		if ("".equals(History.getToken())) {
			History.newItem("list");
		} else {
			History.fireCurrentHistoryState();
		}
	}

	@Override
	public void onValueChange(final ValueChangeEvent<String> event) {
		Window.alert("onValueChange" + event.getValue());
		event.getValue();
		doAddNewContact();
	}
}
